// pages/cart/index.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    
    cart:[],
    
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let that = this
    const db = wx.cloud.database()
    db.collection('orderOK').where({
      _id:options.state
    }).get({
      success(res){
        that.setData({
          cart:res.data
        })
      }
    })
  },


    
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  handleChoseAddress(e){
    //获取收货地址
    wx.chooseAddress({
      success: (result) => {
         wx.setStorageSync("address", result);
      },
    });
    
  },
//点击结算
handlePay(e){
  //判断收货地址
  const {address,totalNum} = this.data;
  //获取缓存中的购物车数据
  let cart = wx.getStorageSync('cart')||[];
  let cart1 = wx.getStorageSync('cart')||[];

  for (let index = 0; index < cart1.length; index++) {
    if(cart1[index].checked){
     cart1.splice(index,1)
    }
  }

  //过滤后的购物车数组
  cart = cart.filter(v=>v.checked);
 

  if (!address.userName){
    wx.showToast({
      title: '您还没有选择收货地址',
      icon: 'none',
      mask: false,
    });
    return;
  }
  //选购商品
  if (totalNum == 0) {
    wx.showToast({
      title: '您还没有选择商品',
      icon: 'none',
      mask: false,
    });
    return;
  }


  cart.forEach(v => {
   const db = wx.cloud.database()
   let date = new Date()
   wx.cloud.callFunction({
     name:'update',
     data:{
       _id:v._id,
       gross:v.gross,
       num:v.num
     }
   }).then(res=>{
     console.log("更新成功");
   })
   db.collection("orderOK").add({
    data:{
      _id:v._id,
      address:address.provinceName+""+address.cityName+""+address.countyName+""+address.detailInfo,
      image:v.image,
      num:v.num,
      orderid:date.getFullYear()+""+date.getMonth()+1+""+date.getDate()+""+date.getMilliseconds(),
      paytime:date.getFullYear()+"-"+date.getMonth()+1+"-"+date.getDate()+" "+date.getHours()+":"+date.getMinutes()+":"+date.getMilliseconds(),
      state:1,
      title:v.title,
      userName:address.userName,
      postID:address.postalCode
    },
    success(res){
      console.log("下单成功");
    }
  })
  })
  wx.setStorageSync("cart", cart1);
  //弹窗提示
  wx.showToast({
    title: '下单成功',
    icon: 'success',
  });

  

},
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})